package main

import (
	"crypto/sha256"
	"crypto/sha512"
	"encoding/hex"
	"io"
	"os"
	"path/filepath"
	"time"

	"github.com/astaxie/beego/logs"
	"gopkg.in/yaml.v3"
)

type LatestEntity struct {
	FileName  string    `yaml:"filename"`
	SHA256    string    `yaml:"sha256"`
	SHA512    string    `yaml:"sha512"`
	Size      int64     `yaml:"size"`
	Timestamp time.Time `yaml:"time"`
	Version   string    `yaml:"version"`
}

func BuildLatest(buildinfo *Build) {
	filePath := filepath.Join(Root, "release", buildinfo.SetupName+" "+buildinfo.Version+" Setup.exe")
	// 计算哈希值
	sha256Hash, sha512Hash, err := calculateHashes(filePath)
	if err != nil {
		logs.Error("Calculate Hashes Error:", err)
		return
	}

	// 获取文件信息
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		logs.Error("Get File Info Error:", err)
		return
	}

	latest := &LatestEntity{
		FileName:  fileInfo.Name(),
		Size:      fileInfo.Size(),
		SHA256:    sha256Hash,
		SHA512:    sha512Hash,
		Version:   buildinfo.Version,
		Timestamp: time.Now().UTC(),
	}
	yamlData, err := yaml.Marshal(latest)
	if err != nil {
		logs.Error("Marshal YAML Error:", err)
		return
	}

	err = os.WriteFile(filepath.Join(Root, "release", "latest.yaml"), yamlData, 0644)

	if err != nil {
		logs.Error("Write YAML Error:", err)
		return
	}

	logs.Info("Build Latest Success!")
}

func calculateHashes(filePath string) (string, string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", "", err
	}
	defer file.Close()

	hashSHA256 := sha256.New()
	hashSHA512 := sha512.New()

	// 同时写入两个哈希计算器
	w := io.MultiWriter(hashSHA256, hashSHA512)
	if _, err := io.Copy(w, file); err != nil {
		return "", "", err
	}

	return hex.EncodeToString(hashSHA256.Sum(nil)),
		hex.EncodeToString(hashSHA512.Sum(nil)),
		nil
}
